﻿using System;
using System.Drawing;
using System.Web;
using System.Web.Mvc;
using Infragistics.UltraGauge.Resources;
using IGMVC.Web.Helpers.UltraGauge;
using IGMVC.Web.Helpers;

namespace IGMVC.Web.Helpers.UltraGauge
{
    public static class UltraGaugeExtensions
    {
        //public const string DefaultImageDirectory = "/Content/GaugeImages/";

        public static string LinearGauge(this HtmlHelper html, LinearGaugeData data, int width, int height, string imageFolderUrl)
        {
            var httpContext = html.ViewContext.HttpContext;

            var gauge = new Infragistics.WebUI.UltraWebGauge.UltraGauge();
            new ControlPreset().LoadInto(gauge);

            ((LinearGauge)gauge.Gauges[0]).Scales[0].Axis.SetStartValue(data.Start);
            ((LinearGauge)gauge.Gauges[0]).Scales[0].Axis.SetEndValue(data.End);
            ((LinearGauge)gauge.Gauges[0]).Scales[0].Markers[0].Value = data.Value;

            return renderGauge(gauge, httpContext, new Size(width, height), imageFolderUrl);
        }

        private static string renderGauge(Infragistics.WebUI.UltraWebGauge.UltraGauge gauge, HttpContextBase httpContext, Size size, string imageFolderUrl)
        {
            var imagePath = imageFolderUrl + Guid.NewGuid();
            var filePath = httpContext.Server.MapPath(imagePath);
            gauge.SaveTo(filePath, GaugeImageType.Jpg, size);

            // Render the <img> tag pointing to the saved file
            var tagBuilder = new TagBuilder("img");
            tagBuilder.Attributes.Add("src", imagePath);
            return tagBuilder.ToString();
        }
    }
}
